#pragma once

#include<iostream>
#include<unistd.h>
#include<cstring>
#include<string>
#include"Log.hpp"
#include"Init.hpp"
#include"TcpServer.hpp"

using namespace std;

Init init;

// extern Log log;

class Task
{
public:
    Task(int sockfd, const std::string& clientip, const uint16_t& clientport)
    :_sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {}

    void Run()
    {
        char buffer[4096];
        
        //稳定的只提供一次服务线程就结束, 所以不会出现线程数量特别多的情况
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "client key@ " << buffer << endl;
            string echo_string = init.translate(buffer);

            write(_sockfd, echo_string.c_str(), echo_string.size());
        }
        else if(n == 0)
        {
            log(Info, "quit server close sockfd:%d, client ip:%s, client port:%d", _sockfd, _clientip.c_str(), _clientport);
        }
        else
        {
            log(Warning, "read error, sockfd:%d, client ip:%s, client port:%d", _sockfd, _clientip.c_str(), _clientport);
        }

        close(_sockfd); 
    }

    void operator()()
    {
        Run();
    }

    ~Task()
    {}
private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};